package com.learn.springboot.config.database.redis;

import org.redisson.Redisson;
import org.redisson.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnection;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.Serializable;

/**
 * Redis 配置
 * @author wangxing
 * @version 2020/8/4 12:32 Administrator
 */
@Configuration
public class RedisConfig {
    public static final Logger LOGGER = LoggerFactory.getLogger(RedisConfig.class);

    /**
     * redis序列化配置
     * @param lettuceConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory){
        LOGGER.info("RedisConfig==>{}","redisTemplate");
        RedisTemplate<String,Serializable> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(lettuceConnectionFactory);
        return template;
    }

    /**
     * 向IOC容器中注入redisson对象
     * @return
     */
    @Bean
    public Redisson getRedisson(){
//        设置单机版本 redisson的配置
        Config config = new Config();
        config.useSingleServer().setAddress("redis://192.168.1.150:6379").setDatabase(0);
//        设置集群版的redisson
        /*config.useClusterServers().addNodeAddress("redis://192.168.1.150:6379")
                .addNodeAddress("redis://192.168.1.150:6380")
                .addNodeAddress("redis://192.168.1.150:6381")
                .addNodeAddress("redis://192.168.1.150:6382")
        */
        return (Redisson) Redisson.create(config);
    }

    /**
     * 向容器中注入JedisPool对象
     * @return
     */
    @Bean
    public JedisPool getJedis(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(20);
        jedisPoolConfig.setMaxIdle(10);
        jedisPoolConfig.setMinIdle(5);
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, "192.168.1.150", 6379, 3000,
                null);

        return jedisPool;
    }
}